package com.shoponline.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory sessionFactory;
	public static final ThreadLocal session = new ThreadLocal();
	
	static{
		
		try{
			
			System.out.println("启动初始化...");
			Configuration cfg = new Configuration();
			System.out.println("读取配置文件");
			sessionFactory = cfg.configure().buildSessionFactory();
			System.out.println("初始化SessionFactory成功..");
			
		}catch(Exception e){
			
			System.err.println("初始化SessionFactory失败");
			e.printStackTrace();
			
		}
		
	}
	
	public static Session getSession(){
		
		Session s = (Session)session.get();
		if(s==null){
			
			s = sessionFactory.openSession();
			session.set(s);
			
		}
		return s;
		
	}
	
	public static void main(String[] args){
		
		HibernateUtil.getSession();
		
	}
}
